<!-- 缴费期限-列表 -->
<template>
  <a-modal :title="mdl.title" destroyOnClose :visible="mdl.visibleIndemnifyPay" maskClosable width="1200px"
    @cancel="$emit('done')" @ok="$emit('done')">
    <el-card class="box-card">
      <div slot="header" class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :span="12">
              <a-button icon="plus" style="margin-right: 8px" type="primary" @click="handleAdd">新建</a-button>
              <a-upload
                name="file"
                :multiple="false"
                :action="uploadApi"
                :show-upload-list="false"
                :beforeUpload="beforeUpload"
                :customRequest="customRequest"
              >
                <!-- :action="uploadApi" :customRequest="customRequest" -->
              <!-- @change="handleUpload" -->
                <a-button icon="upload" type="default" style="margin-right:8px;">费率导入</a-button>
              </a-upload>
              <a-button icon="delete" style="margin-right: 8px" type="primary" @click="handleClearAll">清空费率表</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <el-table :data="tableData" border style="width: 100%">
        <el-table-column label="缴费期-类型" prop="payType" align="center">
          <template slot-scope="scope">
            <el-tag v-if="parseInt(scope.row.payType) === 1">趸交</el-tag>
            <el-tag v-else-if="parseInt(scope.row.payType) === 2">年</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="缴费期值" prop="payValue" align="center" />
        <el-table-column label="被保人年龄" align="center">
          <template slot-scope="scope">
            <el-tag>{{scope.row.ageMin}} ~ {{scope.row.ageMax}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排序号" prop="sortOrder" align="center" />
        <el-table-column label="创建时间" prop="createTime" align="center" />
        <el-table-column label="更新时间" prop="updateTime" align="center" />
        <el-table-column fixed="right" align="center" label="操作">
          <template slot-scope="scope">
            <el-link :underline="false" type="primary" @click="handleEdit(scope.row)">编辑</el-link>
            <el-link :underline="false" type="primary" style="margin-left:10px;"
              @click="openPayRate(scope.row)">费率</el-link>
            <el-link :underline="false" type="danger" style="margin-left:10px;"
              @click="handleDelete(scope.row)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>

      <div style="display: flex;justify-content: flex-end;margin: 20px 0 0;">
        <el-pagination :current-page="queryParam.page" :page-size="queryParam.limit" :page-sizes="[10, 20, 50, 100]"
          :total="total" background layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑 -->
    <indemnify-pay-edit :modal="modal" @done="handleOk"></indemnify-pay-edit>

    <!-- 费率 -->
    <indemnify-pay-rate-list :productId="productId" :mdl="modal" @done="handleOk" />
  </a-modal>
</template>

<script>
  import { listByPage, del } from '@/api/aibao/product/pay'
  import { batchImport, clearByIndemnifyId } from '@/api/aibao/product/payRate'
  import indemnifyPayEdit from './components/indemnify-pay-edit'
  import indemnifyPayRateList from '../indemnify-pay-rate/indemnify-pay-rate-list'

  const baseApi = process.env.VUE_APP_API_BASE_URL
  import axios from 'axios'
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import storage from 'store'
  import { Modal } from 'ant-design-vue'

  export default {
    props: {
      productId: {
        type: String,
        default: ''
      },
      mdl: {
        type: Object,
        default: {}
      },
    },
    components: {
      indemnifyPayEdit,
      indemnifyPayRateList
    },
    data() {
      return {
        uploadApi: baseApi + '/pc/aibaoInsuranceIndemnifyPayRate/batchImport',
        queryParam: {
          page: 1,
          limit: 10,
          productId: '',
          productIndemnifyId: '',
        },
        total: 0,
        modal: {
          visible: false, //新增、编辑
          visibleIndemnifyPayRate: false, // 费率
          indemnifyPayId: '', //缴费期限id
          title: '',
          form: {}
        },
        tableData: [],
      }
    },
    methods: {
      query() {
        this.queryParam.page = 1
        this.getTable()
      },
      handleSizeChange(val) {
        this.queryParam.limit = val
        this.getTable()
      },
      handleCurrentChange(val) {
        this.queryParam.page = val
        this.getTable()
      },

      getTable() {
        this.queryParam.productId = this.productId
        listByPage(this.queryParam).then(res => {
          this.tableData = res.data.records
          this.total = parseInt(res.data.total)
        }).catch(() => {})
      },

      handleOk() {
        this.modal.form = {}
        this.modal.visible = false
        this.modal.visibleIndemnifyPayRate = false
        this.queryParam.page = 1
        this.getTable()
      },

      handleAdd() {
        this.modal.form = {
          productId: this.productId, //产品id
          productIndemnifyId: this.mdl.productIndemnifyId, //保障期id
          id: '', //可选责任id
          payType: 2,
          ageMin: 0,
          ageMax: 0,
          payValue: 0,
          sortOrder: 100
        }
        this.modal.visible = true
        this.modal.title = '新增'
      },
      
      // 清空费率表，2025年4月10日15:31:48
      handleClearAll(){   
        Modal.confirm({
          title: '您确认要清空当前保障期下的所有费率吗？',
          onOk: () => {
            clearByIndemnifyId(this.mdl.productIndemnifyId).then(res => {
              this.$message.success('操作成功')
            }).catch(() => {})
          }
        })
      },
      
      beforeUpload(){
        // 配置请求参数，2025年4月10日11:21:05
        // console.log('beforeUpload', 111)
      },
      async customRequest({ file, onSuccess, onError }) {
        const formData = new FormData()
        formData.append('file', file)
        formData.append('productId', this.productId)
        formData.append('indemnifyId', this.mdl.productIndemnifyId)
        try {
          const response = await axios.post(this.uploadApi, formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              'token': storage.get(ACCESS_TOKEN)
            }
          })
          // console.log(response.data, 333)
          let res = response.data;
          if(res.code == 0){
            this.$message.success('上传成功：' + res.data)
          }else {
            this.$message.error('上传失败：' + res.msg)            
          }
          onSuccess(res)
        } catch (error) {
          onError(error)
          this.$message.success('导入失败')
        }
      },
      
      // 费率批量导入，2025年4月10日11:05:30
      handleUpload(e) {
        // this.modal.form = {
        //   productId: this.productId, //产品id
        //   productIndemnifyId: this.mdl.productIndemnifyId, //保障期id
        // }
        console.log('handleUpload', 222)
        if (e.file.status === 'done') {
          this.errorTips = ''
          this.errorUrl = ''
          const res = e.file.response
          console.log(res, 55)
          if (res.code === 0) {
            // 刷新表格
            this.$refs.table.refresh()
            // this.$message.info('导入成功：'+res.data)
            this.$notification.success({
              message: '导入成功',
              description: res.data.msg,
              duration: 5
            })
            // res.data.url：附件下载地址（有可能返回，有可能不返回）
            if(res.data.msg){
              this.errorTips = res.data.msg
            }
            if(res.data.url){
              this.errorUrl = res.data.url
            }
          } else {
            this.$notification.error({
              message: '导入失败|'+res.code,
              description: res.msg,
              duration: 5
            })
            if(res.data.msg){
              this.errorTips = res.data.msg
            }
            if(res.data.url){
              this.errorUrl = res.data.url
            }
            if (res.code === 401001) {
              this.$store.dispatch('Logout').then(() => {
                setTimeout(() => {
                  window.location.reload()
                }, 1500)
              })
            }
          }
        }
      },

      handleEdit(record) {
        this.modal.form = {
          productId: this.productId, //产品id
          productIndemnifyId: this.mdl.productIndemnifyId, //保障期id
          id: record.id, //可选责任id
          payType: record.payType,
          ageMin: record.ageMin,
          ageMax: record.ageMax,
          payValue: record.payValue,
          sortOrder: record.sortOrder
        }
        this.modal.visible = true
        this.modal.title = '编辑'
      },
      handleDelete(record) {
        // 删除，2025年1月18日17:17:04
        del([record.id]).then(res => {
          this.queryParam.page = 1
          this.getTable()
          this.$message.success('删除成功')
        }).catch(() => {})
      },

      // 打开-费率
      openPayRate(record) {
        this.modal.productId = this.productId //产品id
        this.modal.productIndemnifyId = this.mdl.productIndemnifyId //保障期id
        this.modal.indemnifyPayId = record.id //缴费期限id
        this.modal.visibleIndemnifyPayRate = true
        this.modal.title = '费率'
      },
    },
    watch: {
      mdl: {
        handler(value) {
          if (value.visibleIndemnifyPay) {
            this.queryParam.productId = this.productId
            this.queryParam.productIndemnifyId = this.mdl.productIndemnifyId
            this.getTable()
          }
        },
        deep: true
      }
    },
  }
</script>

<style lang="less" scoped>
  .view-video {
    position: relative;

    .close {
      position: absolute;
      right: 15px;
      top: 0;
      cursor: pointer;
    }
  }

  /deep/.ant-modal-body {
    max-height: calc(80vh - 150px);
    overflow-y: auto;

    &::-webkit-scrollbar {
      width: 6px;
      /*高宽分别对应横竖滚动条的尺寸*/
      height: 1px;
    }

    &::-webkit-scrollbar-thumb {
      // -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
      background: #e3e3e6;
      border-radius: 6px;
    }

    &::-webkit-scrollbar-track {
      background: transparent;
      // -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
      border-radius: 5px;
    }
  }
</style>